import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalService} from "ng-zorro-antd/modal";
import {CustomService} from "../../../shared/services/custom.service";
import {ProductService} from "../../../shared/services/product/product.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ConfigService} from "../../../shared/services/config.service";
import {SellService} from "../../../shared/services/product/sell.service";
import {CustomerService} from "../../../shared/services/product/customer.service";
import * as moment from 'moment';

@Component({
  selector: 'app-history',
  templateUrl: './history.component.html',
  styleUrls: ['./history.component.scss']
})
export class HistoryComponent implements OnInit, OnDestroy {

    option: any = {
        range: [],
        current: 1,
        fields: ['code'],
        keyword: '',
        catalog: 'all',
        category: 'all',
        catalogs: [],
        categories: [],
        paid: 'all',
        customer: null,
        customers: [],
        product: null,
        products: []
    };

    page: any = [];
    sells: any = [];
    _sells: any = [];

    _products: any = [];

    constructor(private router: Router, public route: ActivatedRoute, private sellService: SellService, private customerService: CustomerService, private productService: ProductService, private customService: CustomService, public configService: ConfigService,
                private message: NzMessageService, private modal: NzModalService) {
    }

    async ngOnInit() {
        this.option.catalogs = this.customService.product.catalogs;
        this._products = await this.productService.getAll().toPromise();
        this.option.products = [...this._products];
        this.option.customers = await this.customerService.getAll().toPromise();

        this.option.range = [moment().startOf('month').toDate(), moment().endOf('month').toDate()];
        this.sellService.getByDate(moment().startOf('month'), moment().endOf('month')).subscribe( res => {
            this._sells = res;
            this.filter();
        })
    }

    ngOnDestroy(): void {

    }

    changeDate(result: Date[]): void {
        this.sellService.getByDate(moment(result[0]).startOf('day'), moment(result[1]).endOf('day')).subscribe( res => {
            this._sells = res;
            this.filter();
        });
    }

    filterproduct() {
        this.option.products = this._products.filter(item => {
            if (this.option.catalog != 'all' && item.catalog.code != this.option.catalog) {
                return false;
            } else {
                if (this.option.category != 'all' && item.category.code != this.option.category) {
                    return false;
                }
            }
            return true;
        });
        this.option.product = null;
        this.filter();
    }

    filter() {
        this.sells = this._sells.filter(item => {
            if (this.option.customer && item.customer._id != this.option.customer._id) {
                return false;
            }
            if (this.option.product) {
                if (item.product._id != this.option.product._id) return false;
            } else {
                if (!this.option.products.find(product => item.product._id == product._id)) return false;
            }
            if (this.option.paid != 'all' && !!item.paid != this.option.paid) {
                return false;
            }
            if (this.option.keyword.trim() === '') {
                return true;
            } else {
                return this.option.fields.some(field => {
                    if (item[field].indexOf(this.option.keyword) != -1) {
                        return true;
                    }
                    return false;
                });
            }
        });
        this.page = this.sells.slice((this.option.current - 1) * 10, this.option.current * 10);
    }

    clear() {
        this.option.keyword = '';
        this.filter();
    }

    total() {
        return this.sells.reduce((acc, cur) => {
            return acc + cur.price * cur.amount;
        },0);
    }

    compareObject(g1: any, g2: any): boolean {
        return g1 && g2 ? g1._id === g2._id : g1 === g2;
    }

    activeType1() {
        if (this.option.catalog == 'all') {
            this.option.categories = [];
        } else {
            const catalog = this.option.catalogs.find(item => item.code == this.option.catalog);
            this.option.categories = catalog.children;
        }
        this.option.category = 'all';
        this.filterproduct();
    }

    activeType2() {
        this.filterproduct();
    }

    clearSelection() {
        this._sells.forEach(sell => {
            sell.checked = false;
        });
    }

    printSelection() {
        if (this.sells.some(sell => sell.checked)) {
            this.sellService.print(this.sells.filter(sell => sell.checked));
            this.clearSelection();
        } else {
            this.message.create("warning", "请先勾选条目！");
        }
    }

    paySelection() {
        this.modal.confirm({
            nzTitle: '提示！',
            nzContent: `是否完成支付选择订单？请确认已到账！`,
            nzOkText: '确定',
            nzOkType: 'primary',
            nzOnOk: () => {
                const sells = this.sells.filter(sell => sell.checked);
                sells.forEach(sell => {
                    sell.paid = true;
                });
                this.sellService.updateMany(sells).subscribe(res => {
                    this.clearSelection();
                    this.message.create("success", "完成支付！");
                });
            }
        });
    }

    unpaySelection() {
        this.modal.confirm({
            nzTitle: '提示！',
            nzContent: `是否取消支付选择订单？请确认未收款！`,
            nzOkText: '确定',
            nzOkType: 'primary',
            nzOnOk: () => {
                const sells = this.sells.filter(sell => sell.checked);
                sells.forEach(sell => {
                    sell.paid = false;
                });
                this.sellService.updateMany(sells).subscribe(res => {
                    this.clearSelection();
                    this.message.create("success", "取消支付！");
                });
            }
        });
    }
}
